package com.zmq.interceptor;

import com.zmq.bean.UserBean;
import com.zmq.utils.redis.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private IRedisService redisService;

    /**
     * 拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("拦截器执行开始");
        //拦截规则：登录认证，接口的安全认证，权限认证，项目访问量的统计
        String sessionID = "";

        //获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            response.sendRedirect("/index.html");
            return false;
        }
        //从Cookies中获取自己想要的cookie
        for (Cookie cookie : cookies) {
            if ("COOKIE_SESSION".equals(cookie.getName())) {
                sessionID = cookie.getValue().toString();
            }
        }
        //cookie不能是空
        if ("".equals(sessionID)) {
            response.sendRedirect("/index.html");
            return false;
        }
        //根据获取到的sessionId获取session信息
        UserBean user = (UserBean) redisService.get(sessionID);
        if (user == null) {
            response.sendRedirect("/index.html");
            return false;
        }
        //给session延长时间
        redisService.setExpire(sessionID, 30*60L, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
